/**
 * Created by oneminute on 2014/4/29.
 */

var fs = require("fs");
var path = require("path");
var async = require("async");
var OSS = require('aliyun-oss');
var gm = require('gm');
var lz = require("./modules")();

lz.Logger.debug(lz.Config.resource.aliyun.oss);

var oss = OSS.createClient(lz.Config.resource.aliyun.oss);

/**
 * 保存图片。
 *
 * @param _name
 * @param _data
 * @param _callback
 */
exports.saveImage = function (_name, _src, _des, _callback) {
    var fulldir = path.join(_des, "/f"),
        thumbdir = path.join(_des, "/t"),
        fullimage = path.join(fulldir, "/", _name),
        thumbimage = path.join(thumbdir, "/", _name),
        thumb_width = 96, thumb_height = 96,
        full_width = 256, full_height = 256;

    if (!fs.existsSync(_des))
        fs.mkdirSync(_des);
    lz.Logger.debug("创建缩略图目录。", thumbdir);
    if (!fs.existsSync(thumbdir))
        fs.mkdirSync(thumbdir, 777);

    lz.Logger.debug("imageManager:handleUserPhoto: name:%s src:%s des:%s thumb_width:%d thumbimage:%s",
        _name, _src, _des, thumb_width, thumbimage);
    images(_src).size(thumb_width).save(thumbimage, {quality: 100});

    lz.Logger.debug("创建全图目录。", fulldir);
    if (!fs.existsSync(fulldir))
        fs.mkdirSync(fulldir, 777);

    images(_src).size(full_width).save(fullimage, {quality: 100});

    _callback(null, "ok");
};

exports.uploadImage = function (_name, _src, _thumbSize, _fullSize, _callback) {
    var tasks = [];
    tasks.push(function (_cb) {
        gm(_src).resize(_thumbSize.width, _thumbSize.height)
            .toBuffer(function (_err, _buffer) {
                upload('t', _buffer, function (_err) {
                    _cb(_err);
                });
            });
    });

    tasks.push(function (_cb) {
        gm(_src).resize(_fullSize.width, _fullSize.height)
            .toBuffer(function (_err, _buffer) {
                upload('f', _buffer, function (_err) {
                    _cb(_err);
                });
            });
    });

    function upload(_type, _buf, _callback) {
        lz.Logger.debug('imageManager:uploadImage: 开始上传%s类型的图片。', _type);
        oss.putObject({
            bucket: lz.Config.resource.aliyun.bucket,
            object: _type + '_' + _name,
            source: _buf,
            headers: {
                'Content-Type': 'image/jpg'
            }
        }, function (_err, _res) {
            if (_err) {
                lz.Logger.error('imageManager:uploadImage: 上传%s类型的图片失败: ', _type, _err);
                _callback(_err);
            } else {
                lz.Logger.debug('imageManager:uploadImage: 上传%s类型的图片成功.', _type);
                _callback(null);
            }
        });
    }

    async.series(tasks, function (_err) {
        if (_callback) {
            if (_err) {
                _callback(lz.Config.errors.getError(lz.Config.errors.IMAGE_ERROR, _err));
            } else {
                _callback(null);
            }
        }
    });
};

/**
 *  处理用户头像
 * @param {Object} uobj  用户对象
 * @param {Object} photo  用户头像
 * @param {Function} cb
 */
exports.handleUserPhoto = function (_photo, _callback) {
    var self = this;
    //var des = path.normalize(__dirname + "/../../public/images");
    var name = lz.Utils.getUUID() + ".jpg";
    var src = _photo.path;
    lz.Logger.debug("imageManager:handleUserPhoto: ", name, src);

    self.uploadImage(name, src, lz.Config.image.thumbsize,
        lz.Config.image.fullsize, function (_err) {
            if (_err) {
                _callback(_err);
                return;
            }
            _callback(null, name);
        });
};

exports.handleGoodsPhotos = function (_files, _callback) {
    lz.Logger.debug("imagemanager:handleGoodsPhotos: invoke.", _files);
    var self = this;
    var photonames = [];
    for (var i = 0; i < _files.length; i++) {
        var name = lz.Utils.getUUID() + ".jpg";
        photonames.push(name);
        var src = _files[i];
        lz.Logger.debug("imageManager:handleGoodsPhotos: ", name, src);

        exports.uploadImage(name, src, lz.Config.image.thumbsize,
            lz.Config.image.userfullsize, function (_err) {
                lz.Logger.debug("ImageManager:handleGoodsPhotots: 上传图片(%s)成功", name);
            });
    }

    _callback(null, photonames);
};

exports.removePhotos = function (_photos, _callback) {
    if (!_photos) return;
    var photos = [];
    if (typeof(_photos) == 'array') {
        photos = _photos;
    } else if (typeof(_photos) == 'string') {
        photos.push(_photos);
    } else {
        _callback();
        return;
    }

    var tasks = [];

    function deleteImage(_name, _type) {
        return function (_cb) {
            oss.deleteObject({
                bucket: lz.Config.resource.aliyun.bucket,
                object: _type + '_' + _name
            }, function (_err) {
                _cb(null);
            });
        }
    }

    for (var i = 0; i < photos.length; i++) {
        if (photos[i].length > 0) {
            tasks.push(deleteImage(photos[i], 't'));
            tasks.push(deleteImage(photos[i], 'f'));
        }
    }
    async.parallel(tasks, function () {
        lz.Logger.debug('imageManager:removeGoodsPhotos: 删除商品图片完毕。');
        if (_callback) {
            _callback();
        }
    });

};

exports.getPhoto = function (_photoName, _prefix) {
    if (!_photoName) return "";
    if (!_prefix) _prefix = 't';
    return 'http://' + lz.Config.resource.aliyun.bucket + '.' +
        lz.Config.resource.aliyun.oss.host + '/' + _prefix + "_" + _photoName;
};
